package db

import (
	"fmt"
	"gitee.com/DonHz/cloud-file-storage/db/mydb"
	"gitee.com/DonHz/cloud-file-storage/model"
)

func OnFileUploadFinished(filehash string, filename string, filesize int64, fileaddr string) bool {
	res := mydb.DB.Exec("insert ignore into tbl_file (`file_sha1`, `file_name`, `file_size`, `file_addr`, `status`) values (?, ?, ?, ?, 1)",
		filehash, filename, filesize, fileaddr)
	if res.RowsAffected == 0 || res.Error != nil {
		fmt.Println("文件上传到数据库失败：", filename, "error：", res.Error)
		return false
	}
	return true
}

// 从Mysql中获取文件元信息
func GetFileMeta(filehash string) (model.TableFile, error) {
	var tfile model.TableFile
	res := mydb.DB.Where("file_sha1 = ? and status = 1", filehash).First(&tfile)
	if res.Error != nil {
		return model.TableFile{}, res.Error
	}
	return tfile, nil
}

// UpdateFileLocation : 更新文件的存储地址(如文件被转移了)
func UpdateFileLocation(filehash string, fileaddr string) bool {
	ret := mydb.DB.Model(&model.TableFile{}).Where("file_sha1 = ?", filehash).Update("file_addr", fileaddr)
	if ret.Error != nil {
		fmt.Printf("更新文件location失败, filehash:%s", filehash)
		return false
	}
	return true
}
